<?php

include_once $_SERVER['DOCUMENT_ROOT'].'/functions/password/bdd.php';

if(isset($_POST['token'])){
    
    $token = $_POST['token'];
    
    session_start();

    try {
        $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
        $bdd = new PDO('mysql:host=localhost;dbname=origavion', 'origavion', get_bdd_password(), $pdo_options);
    } catch (Exception $e) {
        die($e->getmessage());
    }

    $prep_photos = $bdd->prepare('INSERT INTO photos_tmp(token, adresse, no) VALUES(?, ?, ?)');
    $prep_get_nb = $bdd->prepare('SELECT * FROM nb_photos_tmp WHERE token=?');
    $prep_nb_photos = $bdd->prepare('UPDATE nb_photos_tmp SET nb=nb+1 WHERE token=?');

    $img_upload = curl_init("http://www.imageshack.us/upload_api.php");

    curl_setopt($img_upload, CURLOPT_CONNECTTIMEOUT, 240);
    curl_setopt($img_upload, CURLOPT_TIMEOUT, 0);
    curl_setopt($img_upload, CURLOPT_POST, true);
    curl_setopt($img_upload, CURLOPT_POSTFIELDS, array( "optsize"   => "500x320",
                                                        "optimage"  => "1",
                                                        "rembar"    => "yes",
                                                        "public"    => "no",
                                                        "key"       => "068BDGKPf62ab9dcc4732eef3555c133994b9983",
                                                        "url"       => "www.origavion.tk/uploads/" . $_POST['file']));
    curl_setopt($img_upload, CURLOPT_RETURNTRANSFER, true);

    $page_reponse = curl_exec($img_upload);
    curl_error($img_upload);
    curl_close($img_upload);

    $xmlparser = simplexml_load_string($page_reponse);
    if ($xmlparser->links) {
        foreach ($xmlparser->links as $liens) {
            $url_image = (string) $liens->image_link;
        }
    } else {
        exit("erreur");
    }

 
    $prep_get_nb->execute(array($token));
    $nb = $prep_get_nb->fetch();
    $prep_photos->execute(array($token, $url_image, $nb['nb']));
    $prep_nb_photos->execute(array($token));

    echo $url_image;

    unlink($_SERVER['DOCUMENT_ROOT'].'/uploads/' . $_POST['file']);

} else {
    echo 'erreur';
}
?>
